package com.tianhua.javs.core.func;

import com.google.common.collect.Lists;
import com.tianhua.javs.client.func.IBusinessTranslatorFunc;
import com.tianhua.javs.client.func.ITranslatorFunc;
import com.tianhua.javs.core.annotations.Segment;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description:
 * date: 2022/2/12
 *
 * @author shenshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service
public class TranslatorContainer implements ApplicationContextAware {

    private static Map<String,List<ITranslatorFunc>> translatorFuncMap = new HashMap<>();
    private static Map<String,List<IBusinessTranslatorFunc>> businessTranslatorFuncMap = new HashMap<>();

    public List<ITranslatorFunc> getByScriptFuncBean(String scriptFuncBeanName){
        return translatorFuncMap.get(scriptFuncBeanName);
    }

    public List<IBusinessTranslatorFunc> getByBusinessScriptFuncBean(String businessScriptFuncBeanName){
        return businessTranslatorFuncMap.get(businessScriptFuncBeanName);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> segmentBeanMap = applicationContext.getBeansWithAnnotation(Segment.class);


        for (Map.Entry<String, Object> entry : segmentBeanMap.entrySet()) {
            Segment segment = AopUtils.getTargetClass(entry.getValue()).getAnnotation(Segment.class);
            if(StringUtils.isEmpty(segment.funcTag())){
                List<ITranslatorFunc> translatorFuncList = translatorFuncMap.get(segment.scriptFuncBean());
                if(CollectionUtils.isEmpty(translatorFuncList)){
                    translatorFuncList = Lists.newArrayList((ITranslatorFunc) entry.getValue());
                }else {
                    translatorFuncList.add((ITranslatorFunc) entry.getValue());
                }
                translatorFuncMap.put(segment.scriptFuncBean(), translatorFuncList);
            }else {
                List<IBusinessTranslatorFunc> translatorFuncList = businessTranslatorFuncMap.get(segment.scriptFuncBean());
                if(CollectionUtils.isEmpty(translatorFuncList)){
                    translatorFuncList = Lists.newArrayList((IBusinessTranslatorFunc) entry.getValue());
                }else {
                    translatorFuncList.add((IBusinessTranslatorFunc) entry.getValue());
                }
                businessTranslatorFuncMap.put(segment.scriptFuncBean(), translatorFuncList);
            }

        }
    }
}
